package com.sx.medicinecard.controller;


import cn.hutool.core.util.IdUtil;
import cn.hutool.core.util.ObjectUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.alipay.api.AlipayApiException;
import com.alipay.api.AlipayClient;
import com.alipay.api.AlipayConfig;
import com.alipay.api.DefaultAlipayClient;
import com.alipay.api.domain.AgreementParams;
import com.alipay.api.domain.AlipayTradePayModel;
import com.alipay.api.request.AlipayMerchantTradecomplainBatchqueryRequest;
import com.alipay.api.request.AlipayTradePayRequest;
import com.alipay.api.response.AlipayMerchantTradecomplainBatchqueryResponse;
import com.alipay.api.response.AlipayTradePayResponse;
import com.aliyun.openservices.log.exception.LogException;
import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.google.protobuf.ServiceException;
import com.sx.medicinecard.common.MyThreadPoolSingleton;
import com.sx.medicinecard.common.ResponseResult;
import com.sx.medicinecard.entity.*;
import com.sx.medicinecard.entity.dto.HeyeCardUsedDto;
import com.sx.medicinecard.entity.notify.*;
import com.sx.medicinecard.mapper.*;
import com.sx.medicinecard.service.*;
import com.sx.medicinecard.utils.*;
import io.swagger.annotations.ApiOperation;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Controller;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.math.BigDecimal;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.time.LocalDate;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;


/**
 * 阿里巴巴回调
 */

@RestController
@RequestMapping("/api/alipay")
@Slf4j
public class AlipayCallbackController {

    @Value("${duodian.channelCode}")
    private String duoDianChannelCode;

    @Resource
    private SxChannelInfoMapper sxChannelInfoMapper;

    @Resource
    private SxSignContractMapper sxSignContractMapper;

    @Resource
    private SxAliAccountInfoMapper sxAliAccountInfoMapper;

    @Resource
    private SxOrderInfoMapper sxOrderInfoMapper;

    @Resource
    private SxEquityCardInfoMapper sxEquityCardInfoMapper;

    private static String SUCCESS = "success";
    private static String ERROR = "error";

    @Value("${heye.key}")
    private String HYKey;

    @Value("${heye.buyBenefits}")
    private String heyeBuyBenefitsUrl;

    @Value("${youku.channelCode}")
    private String youkuChannelCode;

    @Value("${oppo.channelCode}")
    private String oppoChannelCode;

    @Value("${jparking.channelCode}")
    private String jparkChannelCode;

    @Value("${jparking.channelCode002}")
    private String jparkChannelCode002;
    @Value("${jparking.channelCode003}")
    private String jparkChannelCode003;

    @Value("${bianxianmao.channelCode}")
    private String bianxianmaoChannelCode;

    @Value("${cpa.channelCode}")
    private String cpaChannelCode;

    @Value("${nuohe.channelCode}")
    private String nuoheChannelCode;

    @Resource
    private SxUserRecordInfoService sxUserRecordInfoService;

    @Resource
    private AlipayCallbackService alipayCallbackService;

    @Resource
    private SxPayUrlInfoMapper sxPayUrlInfoMapper;

    @Resource
    private SmsVerificationUtils smsVerificationUtils;

    @Resource
    private SxSignContractBrushMapper sxSignContractBrushMapper;

    @Resource
    private SxOrderInfoBrushMapper sxOrderInfoBrushMapper;

    @Resource
    private SxSignContractBrushService sxSignContractBrushService;

    @Resource
    private SxUserPayInfoService sxUserPayInfoService;

    @Resource
    private SxSignContractService sxSignContractService;

    @Resource
    private SxCardSecretMapper sxCardSecretMapper;

    @Resource
    private HyService hyService;

    @Autowired
    private AliLogUtils aliLogUtils;

    private static final ScheduledExecutorService scheduledExecutorService = Executors.newScheduledThreadPool(1);

    /**
     * 支付并签约的支付回调接口
     *
     * @param request
     * @param
     * @return
     */
    @PostMapping("/signAndPayCallBack")
    @ApiOperation("支付并签约的支付回调接口")
    @Transactional
    public String signAndPayCallBack(HttpServletRequest request) {
        try {
            log.info("进入支付宝签约并支付的支付回调--》");
            JSONObject signCallBackJson = new JSONObject();
            Map<String, String[]> requsetMap = request.getParameterMap();

            for (Map.Entry<String, String[]> stringEntry : requsetMap.entrySet()) {
                signCallBackJson.put(stringEntry.getKey(), stringEntry.getValue()[0]);
            }
            //获取签约id
//            String signId = signCallBackJson.getString("out_trade_no");
            String signId = signCallBackJson.getJSONObject("passback_params").getString("signId");
            String payTime = signCallBackJson.getString("gmt_payment");
            QueryWrapper<SxSignContract> sxSignContractQueryWrapper = new QueryWrapper<>();
            sxSignContractQueryWrapper.eq("sign_id", signId);
            List<SxSignContract> sxSignContractList = sxSignContractMapper.selectList(sxSignContractQueryWrapper);
            //如果返回参数包含退款金额字段，就是部分退款时的回调，此时不处理
            if (StringUtils.isNotBlank(signCallBackJson.getString("refund_fee"))) {
                return SUCCESS;
            }
            if (!sxSignContractList.isEmpty()) {
                SxSignContract sxSignContract = sxSignContractList.get(0);
                String phoneNo = sxSignContract.getPhoneNo();
                log.info(phoneNo + "进入支付宝签约并支付的支付回调" + signCallBackJson);
                aliLogUtils.pushLogToAli(IPUtils.getRequestIP(request), request.getRequestURL().toString(), phoneNo, "支付宝签约并支付的支付回调", "", signCallBackJson.toString());

                String yuankeOrderNo = signCallBackJson.getString("out_trade_no");
                if (signCallBackJson.containsKey("buyer_id")){
                    String buyerId = signCallBackJson.getString("buyer_id");
                    if (ObjectUtil.isEmpty(sxSignContract.getAlipayUserId())){
                        sxSignContract.setAlipayUserId(buyerId);
                    }
                }

                //创建订单
                SxOrderInfo orderInfo = alipayCallbackService.createOrder(sxSignContract, yuankeOrderNo, signCallBackJson);

                //根据渠道编码获取渠道信息
                String channelCode = sxSignContract.getChannelCode();
                LambdaQueryWrapper<SxChannelInfo> queryWrapper = Wrappers.lambdaQuery();
                queryWrapper.eq(SxChannelInfo::getChannelCode, channelCode);
                SxChannelInfo sxChannelInfo = sxChannelInfoMapper.selectOne(queryWrapper);
                //查询该用户下方是否有权益卡 包括失效和失效的
                LambdaQueryWrapper<SxEquityCardInfo> wrapper = Wrappers.lambdaQuery();
                wrapper.eq(SxEquityCardInfo::getPhoneNo, phoneNo);
                Long num = sxEquityCardInfoMapper.selectCount(wrapper);
                orderInfo.setPayTime(payTime);
                //根据签约渠道查询产品类型
                if (ObjectUtil.isEmpty(sxChannelInfo.getProductType()) || "0".equals(sxChannelInfo.getProductType())) {
                    //通知荷叶
                    alipayCallbackService.notifyHYPay(orderInfo, num == 0 ? "1" : "0");
                    //通知下游
                    alipayCallbackService.notifyDownStreamPay(sxSignContract, orderInfo);
                }else if ("1".equals(sxChannelInfo.getProductType()) || "2".equals(sxChannelInfo.getProductType())) {
                    //99元vip或海业49.9元权益卡
                    alipayCallbackService.notifyHaiYeDownStreamPay(sxSignContract, orderInfo);
                }
                //通知捷停车
                if (jparkChannelCode.equals(channelCode) || jparkChannelCode002.contains(channelCode) || jparkChannelCode003.equals(channelCode)) {
                    alipayCallbackService.notifyJparkingPay(sxSignContract, orderInfo);
                }
                SxAliAccountInfo sxAliAccountInfo = sxAliAccountInfoMapper.selectById(sxSignContract.getAliAccountId());

                if (ObjectUtil.isNotEmpty(sxAliAccountInfo.getProductType()) && "1".equals(sxAliAccountInfo.getProductType())){
                    scheduledExecutorService.schedule(()->{
                        SxSignContract signContract = sxSignContractMapper.selectById(sxSignContract.getSignId());
                        alipayCallbackService.notifyJZTPay(orderInfo,signContract,"0");
                    },15,TimeUnit.SECONDS);
                }

                //通知变现猫
                if (bianxianmaoChannelCode.contains(channelCode) && ObjectUtil.isNotEmpty(sxSignContract.getBxmId())) {
                    //查看签约状态
                    if (sxSignContract.getIsSignType().equals("1")) {
                        //立即通知变现猫 签约成功
                        alipayCallbackService.notifyBianxianmao(sxSignContract, 5);
                    } else {
                        //ScheduledExecutorService scheduledExecutorService = Executors.newScheduledThreadPool(1); // 创建一个定时任务执行器
                        scheduledExecutorService.schedule(() -> {
                            SxSignContract signContract = sxSignContractMapper.selectById(sxSignContract.getSignId());

                            try {
                                if (ObjectUtil.isNotEmpty(signContract) && signContract.getIsSignType().equals("1")) {
                                    alipayCallbackService.notifyBianxianmao(signContract, 5);

                                } else {
                                    alipayCallbackService.notifyBianxianmao(signContract, 8);
                                }
                            } catch (Exception e) {
                                log.info("变现猫通知失败");
                            }
                        }, 30, TimeUnit.SECONDS);  //延时30秒查询是否获取到签约信息
                    }
                }
                //通知vivo
//                if (vivoChannelCode.equals(channelCode) || vivoChannelCode001.equals(channelCode)){
//                    alipayCallbackService.notifyVivo(sxSignContract,orderInfo);
//                }
                //通知优酷
//                if (youkuChannelCode.equals(channelCode)){
//                    alipayCallbackService.notifyYouku(sxSignContract,orderInfo);
//                }
                //通知oppo
                if (oppoChannelCode.equals(channelCode)) {
                    alipayCallbackService.notifyOppo(sxSignContract, orderInfo);
                }
                //通知cpa
                if (cpaChannelCode.equals(channelCode)) {
                    //通知cpa
                    alipayCallbackService.notifyCpa(sxSignContract, orderInfo);
                    //通知pp停车
                    alipayCallbackService.notifyPP(sxSignContract, orderInfo);
                }
                //通知诺禾
                if (nuoheChannelCode.equals(channelCode)) {
                    alipayCallbackService.notifyNuohe(sxSignContract, orderInfo);
                }
                //通知海业
                //发送短信
                if (ObjectUtil.isEmpty(sxChannelInfo.getProductType()) || "0".equals(sxChannelInfo.getProductType())) {
                    String  s = smsVerificationUtils.paySuccessSendPay(orderInfo.getPhoneNo(), "药省卡尊享版", "支付宝", String.valueOf(orderInfo.getPayAmount()), DateUtils.dateToStringWithFormat(orderInfo.getCreateTime(), "yyyy-MM-dd"));
                    if ("OK".equals(s)) {
                        //发完短信更新用户状态为已发短信
                        orderInfo.setSendState("1");
                        sxOrderInfoMapper.updateById(orderInfo);
                        log.info(orderInfo.getPhoneNo() + "用户支付成功短信发送成功");
                    }
                }


            } else {
                log.info("根据out_trade_no未查到相关签约信息" + signCallBackJson.toString());
            }
        } catch (Exception e) {
            e.printStackTrace();
            return SUCCESS;
        }
        return SUCCESS;
    }


    /**
     * 签约回调接口
     *
     * @param request
     * @return
     */
    @PostMapping("/signCallBack")
    @ApiOperation("签约回调接口")
    @Transactional
//    @Async
    public String signCallBack(HttpServletRequest request, HttpServletResponse httpServletResponse) throws AlipayApiException, ParseException, ServiceException, InterruptedException, LogException, IOException {
        try {
            log.info("进入支付宝签约回调--》");
            JSONObject signCallBackJson = new JSONObject();
            Map<String, String[]> requsetMap = request.getParameterMap();

            for (Map.Entry<String, String[]> stringEntry : requsetMap.entrySet()) {
                signCallBackJson.put(stringEntry.getKey(), stringEntry.getValue()[0]);
            }
            //向阿里云保存签约日志
            // AliLogUtils.pushLogToAli(IPUtils.getRequestIP(request), externalLogonId, "签约回调", "", signCallBackJson.toString());
            //获取当前时间
            Date nowDate = new Date();

            //获取签约id
            String externalAgreementNo = signCallBackJson.getString("external_agreement_no");
            String alipayUserId = signCallBackJson.getString("alipay_user_id");
            String notifyTime = signCallBackJson.getString("notify_time");
            //根据签约id查询签约表，取出渠道编码以及用户手机号、签约流水号
            QueryWrapper<SxSignContract> sxSignContractQueryWrapper = new QueryWrapper<>();
            sxSignContractQueryWrapper.eq("sign_id", externalAgreementNo);
            List<SxSignContract> sxSignContractList = sxSignContractMapper.selectList(sxSignContractQueryWrapper);
            if (!sxSignContractList.isEmpty()) {
                SxSignContract sxSignContract = sxSignContractList.get(0);
                String phoneNo = sxSignContract.getPhoneNo();
                log.info(phoneNo + "签约回调参数->" + signCallBackJson);
                //向阿里云保存签约日志
                aliLogUtils.pushLogToAli(IPUtils.getRequestIP(request), request.getRequestURL().toString(), phoneNo, "签约回调", "", signCallBackJson.toString());
                //根据签约对象获取支付宝账户id，查询支付宝账户信息
                List<SxAliAccountInfo> accountStatusList = sxAliAccountInfoMapper.selectList(new QueryWrapper<SxAliAccountInfo>().eq("ali_account_id", sxSignContract.getAliAccountId()));
                if (accountStatusList.isEmpty()) {
                    throw new ServiceException("没有可用的支付宝账户，请联系管理员！");
                }
                SxAliAccountInfo sxAliAccountInfo = accountStatusList.get(0);

                //获取渠道信息
                SxChannelInfo channelInfo = sxChannelInfoMapper.selectOne(new QueryWrapper<SxChannelInfo>().eq("channel_code", sxSignContract.getChannelCode()));

                //根据渠道编码获取渠道信息
                LambdaQueryWrapper<SxChannelInfo> queryWrapper = Wrappers.lambdaQuery();
                queryWrapper.eq(SxChannelInfo::getChannelCode, sxSignContract.getChannelCode());
                SxChannelInfo sxChannelInfo = sxChannelInfoMapper.selectOne(queryWrapper);
                if (ObjectUtil.isNotEmpty(sxAliAccountInfo.getProductType())&& "1".equals(sxAliAccountInfo.getProductType())) {
                    alipayCallbackService.notifyJZTDownStreamSign(sxSignContract,sxAliAccountInfo);
                }
                //更新签约表信息
                sxSignContract.setSignSerialNumber(signCallBackJson.get("agreement_no").toString());
                sxSignContract.setLastDeductTime(nowDate);
                if (ObjectUtil.isNotEmpty(channelInfo.getProductType()) && ("1".equals(channelInfo.getProductType()) || "2".equals(channelInfo.getProductType()))) {
                    LocalDate nextDeductDate = LocalDate.now().plusDays(1);
                    sxSignContract.setNextDeductDate(DateUtils.localDateToDate(nextDeductDate));
                    sxSignContract.setDeductType(sxAliAccountInfo.getDeductCycleType());
                    sxSignContract.setDeductCycle(sxAliAccountInfo.getDeductCycle());
                    sxSignContract.setSingleDeductAmount(sxAliAccountInfo.getMaxDeductAmount());
                    sxSignContract.setIsSignType("1");
                    sxSignContract.setIsEffectivePopularize("1");
                    sxSignContract.setBody(signCallBackJson.toString());
                    sxSignContract.setAlipayUserId(alipayUserId);
                    sxSignContract.setUpdateTime(new Date());
                    //更新签约时间，不存数据库，用于发送下游通知
                    sxSignContract.setSignTime(notifyTime);

                    sxSignContractMapper.updateById(sxSignContract);

                    //通知下游签约成功
                    alipayCallbackService.notifyHaiYeDownStreamSign(sxSignContract, sxAliAccountInfo);
                    sxUserRecordInfoService.insertOrUpdateRecode("", "4", sxSignContract.getPhoneNo());
                }else {
                    LocalDate nextDeductDate = LocalDate.now().plusDays(sxAliAccountInfo.getDeductCycle());
                    sxSignContract.setNextDeductDate(DateUtils.localDateToDate(nextDeductDate));
                    sxSignContract.setDeductType(sxAliAccountInfo.getDeductCycleType());
                    sxSignContract.setDeductCycle(sxAliAccountInfo.getDeductCycle());
                    sxSignContract.setSingleDeductAmount(sxAliAccountInfo.getMaxDeductAmount());
                    sxSignContract.setIsSignType("1");
                    sxSignContract.setIsEffectivePopularize("1");
                    sxSignContract.setBody(signCallBackJson.toString());
                    sxSignContract.setAlipayUserId(alipayUserId);
                    sxSignContract.setUpdateTime(new Date());
                    //更新签约时间，不存数据库，用于发送下游通知
                    sxSignContract.setSignTime(notifyTime);

                    sxSignContractMapper.updateById(sxSignContract);

                    //通知下游签约成功
                    alipayCallbackService.notifyDownStreamSign(sxSignContract, sxAliAccountInfo);

                    sxUserRecordInfoService.insertOrUpdateRecode("", "4", sxSignContract.getPhoneNo());

                //调用支付宝支付
                AlipayClient alipayClient = new DefaultAlipayClient(getAlipayConfig(sxAliAccountInfo));

                // 构造请求参数以调用接口
                AlipayTradePayRequest requestPay = new AlipayTradePayRequest();
                AlipayTradePayModel model = new AlipayTradePayModel();

                // 设置商户订单号
                String yuankeOrderNo = String.valueOf(SnowflakeIdUtils.generateId());
                model.setOutTradeNo(yuankeOrderNo);
                //查询订单表，判断是否是首期，如果是首期，就使用首期金额
                List<SxOrderInfo> sxOrderInfoList = sxOrderInfoMapper.selectList(new QueryWrapper<SxOrderInfo>().eq("phone_no", sxSignContract.getPhoneNo()));
                // 设置订单总金额
                if (sxOrderInfoList.isEmpty()) {
                    model.setTotalAmount(String.valueOf(channelInfo.getFirstDeductAmount()));
                } else {
                    //非首期
                    model.setTotalAmount(String.valueOf(channelInfo.getMaxDeductAmount()));
                }
                // 设置订单标题
                model.setSubject(sxAliAccountInfo.getSubject()); //从支付宝账户信息获取
                model.setBody("源客项目");
                // 设置代扣信息
                AgreementParams agreementParams = new AgreementParams();
                agreementParams.setAgreementNo(signCallBackJson.get("agreement_no").toString());  //
                model.setAgreementParams(agreementParams);
                // 设置产品码
                model.setProductCode(sxAliAccountInfo.getProductCode());  //GENERAL_WITHHOLDING

                requestPay.setBizModel(model);
                requestPay.putOtherTextParam("app_auth_token", sxAliAccountInfo.getAppAuthToken());    //从支付宝账户获取
                log.info(phoneNo + "调用支付宝支付接口请求参数->" + requestPay.getBizModel().toString());
                AlipayTradePayResponse response = alipayClient.execute(requestPay);

                JSONObject responseData = JSONObject.parseObject(response.getBody());


                log.info(phoneNo + "调用支付宝支付接口返回参数->" + responseData.toString());
                aliLogUtils.pushLogToAli(IPUtils.getRequestIP(request), request.getRequestURL().toString(), phoneNo, "支付宝支付", requestPay.getBizModel().toString(), responseData.toString());
                if (response.isSuccess()) {
                    log.info("支付宝支付接口调用成功！");

                    JSONObject payData = JSONObject.parseObject(responseData.get("alipay_trade_pay_response").toString());
                    String payTime = payData.getString("gmt_payment");

                    //创建订单
                    SxOrderInfo orderInfo = alipayCallbackService.createOrder(sxSignContract, yuankeOrderNo, payData);
                    //通知荷叶支付成功
                    alipayCallbackService.notifyHYPay(orderInfo, sxOrderInfoList.isEmpty() ? "1" : "0");
                    //通知下游支付成功
                    orderInfo.setPayTime(payTime);
                    alipayCallbackService.notifyDownStreamPay(sxSignContract, orderInfo);

                    String channelCode = sxSignContract.getChannelCode();
                    //通知捷停车下单成功
                    if (jparkChannelCode.equals(channelCode) || jparkChannelCode002.contains(channelCode) || jparkChannelCode003.equals(channelCode)) {
                        alipayCallbackService.notifyJparkingPay(sxSignContract, orderInfo);
                    }
                    //通知变现猫
                    if (bianxianmaoChannelCode.contains(channelCode) && ObjectUtil.isNotEmpty(sxSignContract.getBxmId())) {
                        alipayCallbackService.notifyBianxianmao(sxSignContract, 5);
                    }
                    //通知vivo
//                    if (vivoChannelCode.equals(channelCode) || vivoChannelCode001.equals(channelCode)){
//                        alipayCallbackService.notifyVivo(sxSignContract,orderInfo);
//                    }
                    //通知优酷
//                    if (youkuChannelCode.equals(channelCode)){
//                        alipayCallbackService.notifyYouku(sxSignContract,orderInfo);
//                    }
                    //通知oppo
                    if (oppoChannelCode.equals(channelCode)) {
                        alipayCallbackService.notifyOppo(sxSignContract, orderInfo);
                    }
                    //通知CPA
                    if (cpaChannelCode.equals(channelCode)) {
                        alipayCallbackService.notifyCpa(sxSignContract, orderInfo);
                        //通知pp停车
                        alipayCallbackService.notifyPP(sxSignContract, orderInfo);
                    }
                    //通知诺禾
                    if (nuoheChannelCode.equals(channelCode)) {
                        alipayCallbackService.notifyNuohe(sxSignContract, orderInfo);
                    }
                    //记录用户操作信息
                    sxUserRecordInfoService.insertOrUpdateRecode("", "5", sxSignContract.getPhoneNo());

                    //发送短信
                    String s = smsVerificationUtils.paySuccessSendPay(orderInfo.getPhoneNo(), "药省卡尊享版", "支付宝", String.valueOf(orderInfo.getPayAmount()), DateUtils.dateToStringWithFormat(orderInfo.getCreateTime(), "yyyy-MM-dd"));
                    if ("OK".equals(s)) {
                        //发完短信更新用户状态为已发短信
                        orderInfo.setSendState("1");
                        sxOrderInfoMapper.updateById(orderInfo);
                        log.info(orderInfo.getPhoneNo() + "用户支付成功短信发送成功");
                    }

                    if (duoDianChannelCode.equals(channelInfo.getParentChannelCode())) {
                        log.info("重点监控渠道下单，准备发送卡密");

                        if (sxOrderInfoList.isEmpty()) {
                            log.info("是首期支付，确定发送卡密");

                            //查询卡密
                            SxCardSecret sxCardSecret = sxCardSecretMapper.selectOne(new QueryWrapper<SxCardSecret>().eq("card_secret_status", "0").orderByDesc("card_secret_content").last(" limit 1"));
                            if (sxCardSecret != null) {
                                String sendResult = smsVerificationUtils.sendCardSect(phoneNo, sxCardSecret.getCardSecretContent());
                                JSONObject jsonObject = JSONObject.parseObject(sendResult);
                                log.info("发送卡密短信，返回信息" + jsonObject);
                                String code = jsonObject.getString("Code");
                                if ("OK".equals(code)) {
                                    log.info("卡密发送成功更新卡密状态");
                                    sxCardSecret.setCardSecretStatus("1");
                                    sxCardSecret.setUsePhoneNo(phoneNo);
                                    sxCardSecret.setUpdateTime(nowDate);
                                    sxCardSecretMapper.updateById(sxCardSecret);
                                }
                            } else {
                                log.info("已经没有可用卡密，短信未发送");
                            }

                        }
                    }
                } else {
                    log.error("支付宝支付接口调用失败！");
                }
                }
            }
        } catch (Exception e) {
            return SUCCESS;
        }
        return SUCCESS;
    }


    /**
     * 取消签约回调接口
     *
     * @return
     */
    @PostMapping("/cancelSign")
    @ApiOperation("签约并支付的签约/取消签约回调接口")
    @Transactional
    public String cancelSign(HttpServletRequest request, HttpServletResponse httpServletResponse) throws IOException {
        try {
            log.info("进入支付宝签约并支付或解约回调--》");
            JSONObject cancelSignJson = new JSONObject();
            Map<String, String[]> requsetMap = request.getParameterMap();

            for (Map.Entry<String, String[]> stringEntry : requsetMap.entrySet()) {
                cancelSignJson.put(stringEntry.getKey(), stringEntry.getValue()[0]);
            }
            String status = cancelSignJson.getString("status");
            //获取当前时间
            Date nowDate = new Date();
            //获取签约id
            String externalAgreementNo = cancelSignJson.getString("external_agreement_no");
            String alipayUserId = cancelSignJson.getString("alipay_user_id");
            String notifyTime = cancelSignJson.getString("notify_time");
            //根据签约id查询签约表，取出渠道编码以及用户手机号、签约流水号
            QueryWrapper<SxSignContract> sxSignContractQueryWrapper = new QueryWrapper<>();
            sxSignContractQueryWrapper.eq("sign_id", externalAgreementNo);
            List<SxSignContract> sxSignContractList = sxSignContractMapper.selectList(sxSignContractQueryWrapper);

            if (!sxSignContractList.isEmpty()) {
                SxSignContract sxSignContract = sxSignContractList.get(0);
                String phoneNo = sxSignContract.getPhoneNo();
                if (AliStatus.NORMAL.toString().equals(status)) {    //正常签约并支付
                    List<SxAliAccountInfo> accountStatusList = sxAliAccountInfoMapper.selectList(new QueryWrapper<SxAliAccountInfo>().eq("ali_account_id", sxSignContract.getAliAccountId()));
                    SxAliAccountInfo sxAliAccountInfo = accountStatusList.get(0);
                    log.info(phoneNo + "签约并支付的签约回调参数" + cancelSignJson);
                    aliLogUtils.pushLogToAli(IPUtils.getRequestIP(request), request.getRequestURL().toString(), phoneNo, "签约并支付签约", "", cancelSignJson.toString());
                    //更新签约表
                    sxSignContract.setSignSerialNumber(cancelSignJson.get("agreement_no").toString());
                    sxSignContract.setLastDeductTime(nowDate);
                    //根据渠道编码获取渠道信息
                    LambdaQueryWrapper<SxChannelInfo> queryWrapper = Wrappers.lambdaQuery();
                    queryWrapper.eq(SxChannelInfo::getChannelCode, sxSignContract.getChannelCode());
                    SxChannelInfo sxChannelInfo = sxChannelInfoMapper.selectOne(queryWrapper);

                    //下次扣款时间
                    if (ObjectUtil.isNotEmpty(sxChannelInfo.getProductType()) && ("1".equals(sxChannelInfo.getProductType()) ||"2".equals(sxChannelInfo.getProductType()))) {
                        LocalDate nextDeductDate = LocalDate.now().plusDays(1);
                        sxSignContract.setNextDeductDate(DateUtils.localDateToDate(nextDeductDate));
                        sxSignContract.setIsSignType("1");
                        sxSignContract.setIsEffectivePopularize("1");
                        sxSignContract.setBody(cancelSignJson.toString());
                        sxSignContract.setAlipayUserId(alipayUserId);
                        sxSignContract.setUpdateTime(new Date());
                        sxSignContractMapper.updateById(sxSignContract);
                        //通知下游签约成功
                        sxSignContract.setSignTime(notifyTime);
                        alipayCallbackService.notifyHaiYeDownStreamSign(sxSignContract, sxAliAccountInfo);
                    }else {
                        LocalDate nextDeductDate = LocalDate.now().plusDays(sxAliAccountInfo.getDeductCycle());
                        sxSignContract.setNextDeductDate(DateUtils.localDateToDate(nextDeductDate));
                        sxSignContract.setIsSignType("1");
                        sxSignContract.setIsEffectivePopularize("1");
                        sxSignContract.setBody(cancelSignJson.toString());
                        sxSignContract.setAlipayUserId(alipayUserId);
                        sxSignContract.setUpdateTime(new Date());
                        sxSignContractMapper.updateById(sxSignContract);

                        //通知下游签约成功
                        sxSignContract.setSignTime(notifyTime);
                        alipayCallbackService.notifyDownStreamSign(sxSignContract, sxAliAccountInfo);
                    }
                    //通知九州通
                    if (ObjectUtil.isNotEmpty(sxAliAccountInfo.getProductType()) && "1".equals(sxAliAccountInfo.getProductType())) {
                        alipayCallbackService.notifyJZTDownStreamSign(sxSignContract,sxAliAccountInfo);
                    }

                    sxUserRecordInfoService.insertOrUpdateRecode("", "4", sxSignContract.getPhoneNo());
                    sxUserRecordInfoService.insertOrUpdateRecode("", "5", sxSignContract.getPhoneNo());

                    //获取渠道信息
                    SxChannelInfo channelInfo = sxChannelInfoMapper.selectOne(new QueryWrapper<SxChannelInfo>().eq("channel_code", sxSignContract.getChannelCode()));

                    if (duoDianChannelCode.equals(channelInfo.getParentChannelCode())) {
                        log.info("重点监控渠道下单，准备发送卡密");

                        //查询订单表，判断是否是首期
                        List<SxOrderInfo> sxOrderInfoList = sxOrderInfoMapper.selectList(new QueryWrapper<SxOrderInfo>().eq("phone_no", sxSignContract.getPhoneNo()));

                        if (sxOrderInfoList.isEmpty()) {
                            log.info("是首期支付，确定发送卡密");

                            //查询卡密
                            SxCardSecret sxCardSecret = sxCardSecretMapper.selectOne(new QueryWrapper<SxCardSecret>().eq("card_secret_status", "0").orderByDesc("card_secret_content").last(" limit 1"));

                            if (sxCardSecret != null) {
                                String sendResult = smsVerificationUtils.sendCardSect(phoneNo, sxCardSecret.getCardSecretContent());
                                JSONObject jsonObject = JSONObject.parseObject(sendResult);
                                log.info("发送卡密短信，返回信息" + jsonObject);
                                String code = jsonObject.getString("Code");
                                if ("OK".equals(code)) {
                                    log.info("卡密发送成功更新卡密状态");
                                    sxCardSecret.setCardSecretStatus("1");
                                    sxCardSecret.setUsePhoneNo(phoneNo);
                                    sxCardSecret.setUpdateTime(nowDate);
                                    sxCardSecretMapper.updateById(sxCardSecret);
                                }
                            } else {
                                log.info("已经没有可用卡密，短信未发送");
                            }
                        }
                    }

                } else {
                    log.info(phoneNo + "取消签约回调参数" + cancelSignJson);
                    aliLogUtils.pushLogToAli(IPUtils.getRequestIP(request), request.getRequestURL().toString(), phoneNo, "取消签约", "", cancelSignJson.toString());
                    //通知下游解约
                    sxSignContract.setUnsignTime(notifyTime);
                    //根据渠道编码获取渠道信息
                    LambdaQueryWrapper<SxChannelInfo> queryWrapper = Wrappers.lambdaQuery();
                    queryWrapper.eq(SxChannelInfo::getChannelCode, sxSignContract.getChannelCode());
                    SxChannelInfo sxChannelInfo = sxChannelInfoMapper.selectOne(queryWrapper);
                    SxAliAccountInfo sxAliAccountInfo = sxAliAccountInfoMapper.selectById(sxSignContract.getAliAccountId());
                    //好药师账号推送到九州通
                    if (ObjectUtil.isNotEmpty(sxAliAccountInfo.getProductType())&&"1".equals(sxAliAccountInfo.getProductType())){
                        alipayCallbackService.notifyJZTDownStreamCancelSign(sxSignContract);
                    }
                    //下次扣款时间
                    if (ObjectUtil.isNotEmpty(sxChannelInfo.getProductType()) && ("1".equals(sxChannelInfo.getProductType())||"2".equals(sxChannelInfo.getProductType()))) {
                        //通知海业下游解约
                        alipayCallbackService.notifyHaiYeDownStreamCancelSign(sxSignContract);
                    }else {
                        //通知下游解约
                        alipayCallbackService.notifyDownStreamCancelSign(sxSignContract);
                    }
                    String channelCode = sxSignContract.getChannelCode();
                    //通知变现猫
                    if (bianxianmaoChannelCode.contains(channelCode) && ObjectUtil.isNotEmpty(sxSignContract.getBxmId())) {
                        //根据签约ID查询是否有订单
                        boolean exists = sxOrderInfoMapper.exists(Wrappers.lambdaQuery(SxOrderInfo.class).eq(SxOrderInfo::getSignId, sxSignContract.getSignId()));
                        if (exists) {
                            alipayCallbackService.notifyBianxianmao(sxSignContract, 8);
                        }
                    }
                    //更新签约表签约状态
                    if (!"3".equals(sxSignContract.getIsSignType())) {
                        sxSignContract.setIsSignType("0");
                    }
                    sxSignContract.setCancalSignWay("0");
                    sxSignContract.setCancelSingTime(nowDate);
                    sxSignContract.setUpdateTime(nowDate);
                    sxSignContractMapper.updateById(sxSignContract);

                    //更新用户支付情况表的签约状态
                    sxUserPayInfoService.processCancelSign(sxSignContract.getPhoneNo());

                    sxUserRecordInfoService.insertOrUpdateRecode("", "6", sxSignContract.getPhoneNo());
                }
            } else {
                //普通签约表没有查到数据，查一下刷单签约表
                log.info("普通签约表没有查到数据，查一下刷单签约表");
                List<SxSignContractBrush> sxSignContractBrushList = sxSignContractBrushMapper.selectList(new QueryWrapper<SxSignContractBrush>().eq("sign_id", externalAgreementNo));
                if (!sxSignContractBrushList.isEmpty()) {
                    SxSignContractBrush sxSignContractBrush = sxSignContractBrushList.get(0);
                    String phoneNo = sxSignContractBrush.getPhoneNo();
                    //判断是签约并支付的回调还是解约的回调
                    if (AliStatus.NORMAL.toString().equals(status)) {
                        List<SxAliAccountInfo> accountStatusList = sxAliAccountInfoMapper.selectList(new QueryWrapper<SxAliAccountInfo>().eq("ali_account_id", sxSignContractBrush.getAliAccountId()));
                        SxAliAccountInfo sxAliAccountInfo = accountStatusList.get(0);
                        log.info(phoneNo + "(刷单)签约并支付的签约回调参数" + cancelSignJson);
                        aliLogUtils.pushLogToAli(IPUtils.getRequestIP(request), request.getRequestURL().toString(), phoneNo, "(刷单)签约并支付签约回调", "", cancelSignJson.toString());
                        //更新签约表
                        sxSignContractBrush.setSignSerialNumber(cancelSignJson.get("agreement_no").toString());
                        sxSignContractBrush.setLastDeductTime(nowDate);
                        //下次扣款时间
                        LocalDate nextDeductDate = LocalDate.now().plusDays(sxAliAccountInfo.getBrushCycle());
                        sxSignContractBrush.setNextDeductDate(DateUtils.localDateToDate(nextDeductDate));
                        sxSignContractBrush.setIsSignType("1");
                        sxSignContractBrush.setBody(cancelSignJson.toString());
                        sxSignContractBrush.setAlipayUserId(alipayUserId);
                        sxSignContractBrush.setUpdateTime(new Date());
                        sxSignContractBrush.setPayAccount(cancelSignJson.getString("alipay_logon_id"));
                        sxSignContractBrushMapper.updateById(sxSignContractBrush);
                    } else {
                        log.info(phoneNo + "(刷单)取消签约回调参数" + cancelSignJson);
                        aliLogUtils.pushLogToAli(IPUtils.getRequestIP(request), request.getRequestURL().toString(), phoneNo, "(刷单)取消签约回调", "", cancelSignJson.toString());

                        //更新签约表签约状态
                        if (sxSignContractBrush.getIsSignType() != "3") {
                            sxSignContractBrush.setIsSignType("0");
                        }
                        sxSignContractBrush.setCancalSignWay("0");
                        sxSignContractBrush.setCancelSingTime(nowDate);
                        sxSignContractBrush.setUpdateTime(nowDate);
                        sxSignContractBrushMapper.updateById(sxSignContractBrush);
                    }
                } else {
                    log.info("根据external_agreement_no未查到相关签约信息" + cancelSignJson.toString());
                }
            }
            //判断是不是刷单的签约、如果是刷单的签约就去刷单签约表处理

        } catch (Exception e) {
            return SUCCESS;
        }
        return SUCCESS;
    }

    /**
     * 支付并签约的支付回调接口(刷单)
     *
     * @param request
     * @param
     * @return
     */
    @PostMapping("/signAndPayCallBackBrush")
    @ApiOperation("支付并签约的支付回调接口(刷单)")
    @Transactional
    public String signAndPayCallBackBrush(HttpServletRequest request) {
        try {
            log.info("进入支付宝签约并支付的支付(刷单)回调--》");
            JSONObject signCallBackJson = new JSONObject();
            Map<String, String[]> requsetMap = request.getParameterMap();

            for (Map.Entry<String, String[]> stringEntry : requsetMap.entrySet()) {
                signCallBackJson.put(stringEntry.getKey(), stringEntry.getValue()[0]);
            }
            //获取签约id
            String signId = signCallBackJson.getJSONObject("passback_params").getString("signId");
            String payTime = signCallBackJson.getString("gmt_payment");

            List<SxSignContractBrush> sxSignContractBrushList = sxSignContractBrushMapper.selectList(new QueryWrapper<SxSignContractBrush>().eq("sign_id", signId));
            //如果返回参数包含退款金额字段，就是部分退款时的回调，此时不处理
            if (StringUtils.isNotBlank(signCallBackJson.getString("refund_fee"))) {
                return SUCCESS;
            }
            if (!sxSignContractBrushList.isEmpty()) {
                SxSignContractBrush sxSignContractBrush = sxSignContractBrushList.get(0);
                String phoneNo = sxSignContractBrush.getPhoneNo();
                log.info(phoneNo + "进入支付宝签约并支付的支付(刷单)回调" + signCallBackJson);
                aliLogUtils.pushLogToAli(IPUtils.getRequestIP(request), request.getRequestURL().toString(), phoneNo, "支付宝签约并支付的支付(刷单)回调", "", signCallBackJson.toString());

                String yuankeOrderNo = signCallBackJson.getString("out_trade_no");

                //创建(刷单)订单
                sxSignContractBrushService.createOrderBrush(sxSignContractBrush, yuankeOrderNo, "", signCallBackJson);

            } else {
                log.info("根据out_trade_no未查到相关签约信息" + signCallBackJson.toString());
            }
        } catch (Exception e) {
            e.printStackTrace();
            return SUCCESS;
        }
        return SUCCESS;
    }

    /**
     * 签约回调接口
     *
     * @param request
     * @return
     */
    @PostMapping("/signPayCallBackBrush")
    @ApiOperation("签约回调接口(刷单)")
    @Transactional
//    @Async
    public String signCallBackBrush(HttpServletRequest request, HttpServletResponse httpServletResponse) throws AlipayApiException, ParseException, ServiceException, InterruptedException, LogException, IOException {
        try {
            log.info("进入支付宝签约(刷单)回调--》");
            JSONObject signCallBackJson = new JSONObject();
            Map<String, String[]> requsetMap = request.getParameterMap();

            for (Map.Entry<String, String[]> stringEntry : requsetMap.entrySet()) {
                signCallBackJson.put(stringEntry.getKey(), stringEntry.getValue()[0]);
            }
            //获取当前时间
            Date nowDate = new Date();
            //获取签约id
            String externalAgreementNo = signCallBackJson.getString("external_agreement_no");
            String alipayUserId = signCallBackJson.getString("alipay_user_id");
            String notifyTime = signCallBackJson.getString("notify_time");
            //根据签约id查询签约表，取出渠道编码以及用户手机号、签约流水号
            QueryWrapper<SxSignContractBrush> sxSignContractQueryWrapper = new QueryWrapper<>();
            sxSignContractQueryWrapper.eq("sign_id", externalAgreementNo);
            List<SxSignContractBrush> sxSignContractList = sxSignContractBrushMapper.selectList(sxSignContractQueryWrapper);
            if (!sxSignContractList.isEmpty()) {

                SxSignContractBrush sxSignContractBrush = sxSignContractList.get(0);
                List<SxAliAccountInfo> accountStatusList = sxAliAccountInfoMapper.selectList(new QueryWrapper<SxAliAccountInfo>().eq("ali_account_id", sxSignContractBrush.getAliAccountId()));
                SxAliAccountInfo sxAliAccountInfo = accountStatusList.get(0);
                //更新签约表
                sxSignContractBrush.setSignSerialNumber(signCallBackJson.get("agreement_no").toString());
                sxSignContractBrush.setLastDeductTime(nowDate);
                //下次扣款时间
                LocalDate nextDeductDate = LocalDate.now().plusDays(sxAliAccountInfo.getBrushCycle());
                sxSignContractBrush.setNextDeductDate(DateUtils.localDateToDate(nextDeductDate));
                sxSignContractBrush.setIsSignType("1");
                sxSignContractBrush.setBody(signCallBackJson.toString());
                sxSignContractBrush.setAlipayUserId(alipayUserId);
                sxSignContractBrush.setUpdateTime(new Date());
                sxSignContractBrush.setPayAccount(signCallBackJson.getString("alipay_logon_id"));
                sxSignContractBrushMapper.updateById(sxSignContractBrush);
                String phoneNo = sxSignContractBrush.getPhoneNo();
                log.info(phoneNo + "进入支付宝签约(刷单)回调" + signCallBackJson);
                //向阿里云保存签约日志
                aliLogUtils.pushLogToAli(IPUtils.getRequestIP(request), request.getRequestURL().toString(), phoneNo, "签约回调(刷单)", "", signCallBackJson.toString());
                //根据签约对象获取支付宝账户id，查询支付宝账户信息
//                List<SxAliAccountInfo> accountStatusList = sxAliAccountInfoMapper.selectList(new QueryWrapper<SxAliAccountInfo>().eq("ali_account_id", sxSignContractBrush.getAliAccountId()));
//                if (accountStatusList.isEmpty()) {
//                    throw new ServiceException("没有可用的支付宝账户，请联系管理员！(刷单)");
//                }


                //调用支付宝支付
                AlipayClient alipayClient = new DefaultAlipayClient(getAlipayConfig(sxAliAccountInfo));

                // 构造请求参数以调用接口
                AlipayTradePayRequest requestPay = new AlipayTradePayRequest();
                AlipayTradePayModel model = new AlipayTradePayModel();

                // 设置商户订单号
                String yuankeOrderNo = String.valueOf(SnowflakeIdUtils.generateId());
                model.setOutTradeNo(yuankeOrderNo);
                model.setTotalAmount(String.valueOf(sxAliAccountInfo.getBrushAmount()));

                // 设置订单标题
                model.setSubject(sxAliAccountInfo.getSubject()); //从支付宝账户信息获取
                model.setBody(sxAliAccountInfo.getBrushBody()); //从支付宝账户信息获取
                // 设置代扣信息
                AgreementParams agreementParams = new AgreementParams();
                agreementParams.setAgreementNo(signCallBackJson.get("agreement_no").toString());  //
                model.setAgreementParams(agreementParams);
                // 设置产品码
                model.setProductCode(sxAliAccountInfo.getProductCode());  //GENERAL_WITHHOLDING

                requestPay.setBizModel(model);
                requestPay.putOtherTextParam("app_auth_token", sxAliAccountInfo.getAppAuthToken());    //从支付宝账户获取
                log.info(phoneNo + "调用支付宝支付接口请求参数(刷单)->" + requestPay.getBizModel().toString());
                AlipayTradePayResponse response = alipayClient.execute(requestPay);

                JSONObject responseData = JSONObject.parseObject(response.getBody());

                log.info(phoneNo + "调用支付宝支付接口返回参数(刷单)->" + responseData.toString());
                aliLogUtils.pushLogToAli(IPUtils.getRequestIP(request), request.getRequestURL().toString(), phoneNo, "支付宝支付(刷单)", requestPay.getBizModel().toString(), responseData.toString());
                if (response.isSuccess()) {
                    log.info("支付宝支付接口调用成功！(刷单)");
                    //创建(刷单)订单
                    sxSignContractBrushService.createOrderBrushByPay(sxSignContractBrush, yuankeOrderNo, "",JSONObject.parseObject(responseData.getString("alipay_trade_pay_response")));
                } else {
                    log.error("支付宝支付接口调用失败！(刷单)");
                }
            }
        } catch (Exception e) {
            return SUCCESS;
        }
        return SUCCESS;
    }

    /**
     * 荷叶支付并签约的支付回调接口(刷单)
     *
     * @param request
     * @param
     * @return
     */
    @PostMapping("/signAndPayCallBackBrushHy")
    @ApiOperation("荷叶支付并签约的支付回调接口(刷单)")
    @Transactional
    public String signAndPayCallBackBrushHy(HttpServletRequest request) {
        try {
            log.info("进入荷叶支付宝签约并支付的支付(刷单)回调--》");
            JSONObject signCallBackJson = new JSONObject();
            Map<String, String[]> requsetMap = request.getParameterMap();

            for (Map.Entry<String, String[]> stringEntry : requsetMap.entrySet()) {
                signCallBackJson.put(stringEntry.getKey(), stringEntry.getValue()[0]);
            }
            //获取签约id
            String signId = signCallBackJson.getJSONObject("passback_params").getString("signId");
            String payTime = signCallBackJson.getString("gmt_payment");

            List<SxSignContractBrush> sxSignContractBrushList = sxSignContractBrushMapper.selectList(new QueryWrapper<SxSignContractBrush>().eq("sign_id", signId));
            //如果返回参数包含退款金额字段，就是部分退款时的回调，此时不处理
            if (StringUtils.isNotBlank(signCallBackJson.getString("refund_fee"))) {
                return SUCCESS;
            }
            if (!sxSignContractBrushList.isEmpty()) {
                SxSignContractBrush sxSignContractBrush = sxSignContractBrushList.get(0);
                String phoneNo = sxSignContractBrush.getPhoneNo();
                log.info(phoneNo + "进入荷叶支付宝签约并支付的支付(刷单)回调" + signCallBackJson);
                aliLogUtils.pushLogToAli(IPUtils.getRequestIP(request), request.getRequestURL().toString(), phoneNo, "荷叶支付宝签约并支付的支付(刷单)回调", "", signCallBackJson.toString());

                String yuankeOrderNo = signCallBackJson.getString("out_trade_no");

                //激活权益
                String receiveId = hyService.activationRights(sxSignContractBrush.getPhoneNo());
//                String receiveId = JSONObject.parseObject(heyeString).getJSONObject("data").getString("receiveId");

                //创建(刷单)订单
                sxSignContractBrushService.createOrderBrush(sxSignContractBrush, yuankeOrderNo, receiveId, signCallBackJson);

            } else {
                log.info("根据out_trade_no未查到相关签约信息" + signCallBackJson.toString());
            }
        } catch (Exception e) {
            e.printStackTrace();
            return SUCCESS;
        }
        return SUCCESS;
    }


    @PostMapping("/payByYearCallBackUrl")
    public String payByYearCallBackUrl(HttpServletRequest request) throws AlipayApiException, IOException {
        log.info("进入年费版支付的支付/退款回调--》");
        JSONObject payByYearCallBack = new JSONObject();
        Map<String, String[]> requsetMap = request.getParameterMap();

        for (Map.Entry<String, String[]> stringEntry : requsetMap.entrySet()) {
            payByYearCallBack.put(stringEntry.getKey(), stringEntry.getValue()[0]);
        }


        //   AliLogUtils.pushLogToAli(IPUtils.getRequestIP(request), request.getRequestURL().toString(), phoneNo, "支付宝签约并支付的支付回调", "", signCallBackJson.toString());
        String tradeStatus = payByYearCallBack.getString("trade_status");
        if (tradeStatus.equals("TRADE_SUCCESS")) {
            log.info("年费支付回调参数" + payByYearCallBack.toString());
            String yuankeOrderNo = payByYearCallBack.getString("out_trade_no");
            String passbackParams = payByYearCallBack.getString("passback_params");
            JSONObject parseObject = JSONObject.parseObject(passbackParams);
            String phoneNo = parseObject.getString("phoneNo");
            String aliAccountId = parseObject.getString("aliAccountId");
            String payId = parseObject.getString("payId");
            String channelCode = parseObject.getString("channelCode");
            //创建订单
            SxOrderInfo orderInfo = alipayCallbackService.createOrderByYear(phoneNo, aliAccountId, yuankeOrderNo, channelCode, payByYearCallBack);
            //通知荷叶
            alipayCallbackService.notifyHYPay(orderInfo, "1");
            //修改支付状态
            LambdaUpdateWrapper<SxPayUrlInfo> updateWrapper = Wrappers.lambdaUpdate();
            updateWrapper.eq(SxPayUrlInfo::getPayId, payId);
            updateWrapper.set(SxPayUrlInfo::getIsPay, "1");
            sxPayUrlInfoMapper.update(new SxPayUrlInfo(), updateWrapper);
            //查询当前用户是否是月缴版会员
            LambdaQueryWrapper<SxEquityCardInfo> wrapper = Wrappers.lambdaQuery();
            wrapper.eq(SxEquityCardInfo::getPhoneNo, phoneNo);
            wrapper.eq(SxEquityCardInfo::getEffectiveStatus, "1");
            wrapper.eq(SxEquityCardInfo::getVipType, "0");
            wrapper.orderByDesc(SxEquityCardInfo::getCreateTime);
            wrapper.last("limit 1");
            SxEquityCardInfo sxEquityCardInfo = sxEquityCardInfoMapper.selectOne(wrapper);
            if (ObjectUtil.isNotEmpty(sxEquityCardInfo)) {
                sxSignContractService.unSign(phoneNo);
            }
        } else {
            log.info("年费退款回调参数" + payByYearCallBack.toString());
            //年费退款新增退款记录

        }
        //通知下游
        //orderInfo.setPayTime(payTime);
        //alipayCallbackService.notifyDownStreamPay(sxSignContract, orderInfo);
        return SUCCESS;
    }

    private AlipayConfig getAlipayConfig(SxAliAccountInfo sxAliAccountInfo) {
        String privateKey = sxAliAccountInfo.getPrivateKey();
        String alipayPublicKey = sxAliAccountInfo.getAlipayPublicKey();
        AlipayConfig alipayConfig = new AlipayConfig();
        alipayConfig.setServerUrl("https://openapi.alipay.com/gateway.do");
        //alipayConfig.setAppId("2021004137633645");
        alipayConfig.setAppId(sxAliAccountInfo.getAppId());
        alipayConfig.setPrivateKey(privateKey);
        alipayConfig.setFormat("json");
        alipayConfig.setAlipayPublicKey(alipayPublicKey);
        alipayConfig.setCharset("UTF-8");
        alipayConfig.setSignType("RSA2");
        return alipayConfig;
    }

//    public static void main(String[] args) throws AlipayApiException {
//        String privateKey = "MIIEvQIBADANBgkqhkiG9w0BAQEFAASCBKcwggSjAgEAAoIBAQCe0TYz6tUD/3GFvXeDp8Vgae8qL1tspniG/IfgYMZ+yrjBY6Bc+mtiID8VLvH0rkU253C7MJM5FZyVQcn5HrpeUaQGu0pU7wBNawO5jd5nJu4Rouvl99yzYThvk4TeHQafXEUO/lnG3XySoEC+wZoZ6JSJHH24ieP3/kJYuGHQteZxGIutY3nuSUu9GFvCX9tqVrXsQzBifSZrep/1tbYvIrmia9p5NJwdEUxfu8V8RoTDJRn1Fq6oncXGDlkuaAqTk5aR/BEE35dthle97LBbf6nmAEtvzlz0OifBMnD604dmRdgl/Sb0Ch8jMCxhdDGnuPDhymfJ13SqclNuFwFdAgMBAAECggEAM1VOHsPVrGAhkmfmPHC69GnpOwppk5nPNVpklNrS7eKaiy+ngsYSdXoUycUNwdeeWZu/LVILFBVvMjM8lEAhXyEmUmKxKPjDcUKYxp4bd932b07ozsEp3fUbp7zX4m8hV9scGzeNTyECBea0ZrPvGla5xAOog0BWpi7RxRl7zFisLhihh6PsvM8f1Ud94TBCl0tyNKg5sNaLE5GaqHkVxmIsY2xuqqIcsJOD4cAGqxdD5B2VckYRzQNqNHnQksp/xsufmxBVlIhlQmTqxUQX7fDakftXuAv8uyqG3KAX3p/PETV0weVORNprc6feE1m625YqkRiwWD3AVeEoO6zKYQKBgQDe2oXtkZxdsR2GjjC4e3xLtw9ndul5mZPmBW2Po5ol2PmmXxmKK57JyPeEP/7eqVkVNwMFl7UXwkGYNnKuyzbbImhWrBQRBl+8+wdpGxMBZ3//rV0TEa8vpDToe+0+OCNZB8qayIbf0TGDrXwldkT+ZV01nxrVPRbunhgGDEhMCQKBgQC2cGj6BmTEzlbxWYBIl/2htmuUgLSN0Lo3llKyGpdvCUmQG4oS0zar1DaJ9GbQYWBIAAlDDS2GkmCu35+qSJFQ4M6NMtQ7otJZYVhIJhKaJ3W+LQNApCvCpacgqDMyjve0cQ/jOs0PN1WQbNQwWyffxWW/jCwwd6yi9d5OoP0HtQKBgB2bhL2aYd7kwBp3W6u25D2e9ZH2b3BzYf3mbLbvsnQizpA3BEqiHveKFrBgXDky4J378A/XJv0gFtzlJvloEEKu4JPbStM0OJX/9+0T5sOB/7R1UO9Ooyq+MzVL+aoRhUi3y0gjKiAkR+LJsru7adEuoGKWX9dCxYAwStrK2PQZAoGBAJhtawga926Hh5S21rvQYZUPOOsmbbRfRHbVHdq45PVcqR3CJKZ92hvOfpLcpFpOQYdmoFZpWDQrcKQrKte3MdKFQY4vfasl6uHKt1vwk3JArdtq+GC1yeojRXO/lKcVVFhqbn/HzTR9Yvv8MX0FbFdGMjDMCM+l7ZNqIYdIcqBRAoGAcjXLruhsfJG4kZfbtw8Fini+u3yny1y3/OSJLXnVfZEcsBsTGqHf8sx9BRg5mFLP1GzVpfywaf793LlDnJzfb7kf4wn6LcRMNunbOmzr7gzbbPEKDNw/bOZwM0X9uUHNbTQlHrZgkFMFl5bTWrQdjprPICBkohFfPelNvwffqSM=";
//        String alipayPublicKey = "MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAnpabDvlYRs5GGzAC4SBNjyhHNL7L5X9+njpAAy9XrQtgW8A7UhkFj6oEmyNYNHRCUoZpgMLCDg1fSKeEfmyN7HpSIe3dYAN4D9+9P4vR3OXKRgAyEaZ14xpd1m3THJPF4PnkbjAs02Cmpp8PG8PEk4gjGy7eVtZthIVuj3lFx3u12/g5Mp9vejkP4gp09S5k1ItI6/rCnONc7irR4QS8j4zXdKmdeJVHcS5C3RgGZZSjRgsrXZltWguDhLtOx3XwvKI2eTUsQcgn4n0vo/LkX55ZCn+zN9VgBaHS1D5tXLGMfOHi5eTMXfHVHeorgntELe+Rx0rA83GZMRL29xP2nQIDAQAB";
//        String appId = "2021004137633645";
//        AlipayClient alipayClient = new DefaultAlipayClient("https://openapi.alipay.com/gateway.do", appId, privateKey, "json", "GBK", alipayPublicKey, "RSA2");
//        AlipayMerchantTradecomplainBatchqueryRequest request = new AlipayMerchantTradecomplainBatchqueryRequest();
//        request.setBizContent("{" +
//                "  \"target_infos\":[" +
//                "    {" +
//                "      \"target_id\":\"2021004137633645\"," +
//                "      \"target_type\":\"APPID\"" +
//                "    }" +
//                "  ]," +
////                "  \"status\":\"MERCHANT_PROCESSING\"," +
//                "  \"page_size\":10," +
//                "  \"page_num\":1" +
//                "}");
//        request.putOtherTextParam("app_auth_token", "202404BB337a6e49102648cdb291ce713f6f4C24");
//        AlipayMerchantTradecomplainBatchqueryResponse response = alipayClient.execute(request);
//        System.out.println(response.getBody());
//        if (response.isSuccess()) {
//            System.out.println("调用成功");
//        } else {
//            System.out.println("调用失败");
//        }
//    }
}
